package com.ziyueyuwen.xiniao.controller;

import com.suyeer.basic.util.BasicUtil;
import com.suyeer.basic.util.HttpResUtil;
import com.suyeer.basic.util.LogUtil;
import com.suyeer.cache.RedisUtil;
import com.suyeer.fastwechat.util.FwUtil;
import com.ziyueyuwen.xiniao.base.HttpResContent;
import com.ziyueyuwen.xiniao.bean.ZyUser;
import com.ziyueyuwen.xiniao.bean.vo.ZyUserVO;
import com.ziyueyuwen.xiniao.bean.wx.TbWxUserInfo;
import com.ziyueyuwen.xiniao.module.UserLoginCache;
import com.ziyueyuwen.xiniao.service.SubscriptionService;
import com.ziyueyuwen.xiniao.service.ThirdPartService;
import com.ziyueyuwen.xiniao.service.UserService;
import com.ziyueyuwen.xiniao.util.SmsUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.HashMap;

import static com.ziyueyuwen.xiniao.base.BaseUtil.*;
import static com.ziyueyuwen.xiniao.enums.ParamTypeEnum.ZH_PHONE_NUM;
import static com.ziyueyuwen.xiniao.util.ConstUtil.PARAM_CODE;
import static com.ziyueyuwen.xiniao.util.ConstUtil.PARAM_PHONE_NUM;

/**
 * @author jun 2018/10/25
 */
@Controller
@RequestMapping("/")
public class IndexController {

    @Autowired
    private UserService userService;

    @Autowired
    private ThirdPartService thirdPartService;

    @Autowired
    private SubscriptionService subscriptionService;

    @RequestMapping(method = RequestMethod.GET)
    public String index(HttpServletRequest request, Model model) {
        model.addAttribute("port", request.getLocalPort());
        model.addAttribute("wxConfigObj", FwUtil.getJsSdkConfig(request));
        return "/index";
    }

    @RequestMapping(value = "/send_verification_code.do", method = RequestMethod.POST)
    public void sendVerificationCode(@RequestParam(PARAM_PHONE_NUM) String phoneNum) throws Exception {
        HttpResContent<Boolean> hrc = new HttpResContent<>("发送短信验证码");
        // check.
        checkParam(ZH_PHONE_NUM, PARAM_PHONE_NUM, phoneNum);
        // do.
        SmsUtil.industrySMS(phoneNum);
        // result.
        hrc.printLogAndResponse(true);
    }

    @RequestMapping(value = "/test", method = RequestMethod.GET)
    public void test() {
        HttpResContent<HashMap<String, Integer>> hrc = new HttpResContent<>("测试");
        HashMap<String, Integer> hashMap = subscriptionService.getAwardInfo();
        hrc.printLogAndResponse(hashMap);
    }

    @RequestMapping(value = "/login_by_phone_num.do", method = RequestMethod.POST)
    public void loginByPhoneNum(@RequestParam(PARAM_PHONE_NUM) String phoneNum,
                                @RequestParam(PARAM_CODE) String code) throws Exception {
        HttpResContent<Boolean> hrc = new HttpResContent<>("手机号快速登录");
        // check.
        checkParam(ZH_PHONE_NUM, PARAM_PHONE_NUM, phoneNum);
        checkParam(PARAM_CODE, code);
        // do.
        RedisUtil.checkCode(phoneNum, code);
        ZyUser student = userService.getByAccount(phoneNum);
        if (student == null) {
            student = new ZyUser();
            student.setUserAccount(phoneNum);
            student.setUserName(BasicUtil.hidePhoneNum(phoneNum));
            student.setCreateTime(new Date());
            student.setIfSysUser(false);
            student.setIfDelete(false);
            userService.saveStudent(student);
            try {
                TbWxUserInfo tbWxUserInfo = hrc.getWxUserInfo();
                if (tbWxUserInfo != null) {
                    thirdPartService.bindWx(phoneNum, tbWxUserInfo.getWxUserId());
                }
            } catch (Exception e) {
                LogUtil.error(e);
            }
        }
        student.setUserPassword(null);
        hrc.setUserSession(student);
        UserLoginCache.getInstance().add(student.getUserAccount(), hrc.getSessionId());
        hrc.printLogAndResponse(true);
    }

    @RequestMapping(value = "/login.do", method = RequestMethod.POST)
    public void doLogin(String userAccount,
                        String userPassword,
                        HttpServletRequest request,
                        HttpServletResponse response) {
        HttpResContent<String> hrc = new HttpResContent<>(request, response);
        hrc.setFuncDes("登录操作");
        try {
            ZyUserVO user = userService.getUserMessage(userAccount);
            if (user == null) {
                throw new Exception("用户不存在!");
            }
            user.setUserPassword(null);
            hrc.setUserSession(user);
            UserLoginCache.getInstance().add(user.getUserAccount(), hrc.getSessionId());
            saveSuccessMsgAndData(hrc, hrc.getSessionId());
        } catch (Exception e) {
            saveErrorMsgAndData(hrc, e);
        } finally {
            HttpResUtil.writeResult(hrc, true);
        }
    }

    @RequestMapping(value = "/logout.do", method = RequestMethod.POST)
    public void logout(HttpServletRequest request,
                       HttpServletResponse response) {
        HttpResContent<Boolean> hrc = new HttpResContent<>(request, response);
        hrc.setFuncDes("注销操作");
        try {
            hrc.removeUserSession();
            saveSuccessMsgAndData(hrc, true);
        } catch (Exception e) {
            saveErrorMsgAndData(hrc, e);
        } finally {
            HttpResUtil.writeResult(hrc, true);
        }
    }

}
